"""
修改文档格式.docx转为.doc，并保存到docx上级目录中
"""
import pythoncom
import os
from docx import Document
from docx.opc.exceptions import PackageNotFoundError


# 从最后开始替换某字符串几次
def rreplace(s, old, new, occurrence):
    li = s.rsplit(old, occurrence)
    return new.join(li)


# 读取文件夹下的docx文件名列表
def docx_file_name(file_dir):
    file_list = []
    for root, dirs, files in os.walk(file_dir):
        for file in files:
            if os.path.splitext(file)[1] == '.docx':
                file_list.append(os.path.join(root, file))
    return file_list


# docx文件另存为doc
def docx_to_doc(docx_name):
    pythoncom.CoInitialize()
    try:
        doc = Document(docx_name)
        docx_name = rreplace(docx_name, "\\docx\\", "\\", 1)
        doc.save(docx_name.replace(".docx", ".doc"))
    except PackageNotFoundError:
        pass
    finally:
        # 释放资源
        pythoncom.CoUninitialize()


def main():
    file_list = docx_file_name("D:\\文件处理\\2020.8.22-棋牌")
    print("文件数量：", len(file_list))
    for file in file_list:
        docx_to_doc(file)


if __name__ == '__main__':
    main()
